package me.xiaosiqi.service.store.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import me.xiaosiqi.dao.store.QuestionDao;
import me.xiaosiqi.domain.store.Question;
import me.xiaosiqi.factory.MapperFactory;
import me.xiaosiqi.service.store.QuestionService;
import me.xiaosiqi.utils.BeanUtil;
import me.xiaosiqi.utils.TransactionUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author xiaosiqi
 * @date 2021/6/3 14:38
 */
public class QuestionServiceImpl implements QuestionService {
    String uploadDir = "upload";

    @Override
    public void save(List<FileItem> fileItems, String path) {
        SqlSession sqlSession = null;
        Question question = null;
        String fineName = "";
        boolean flag = false;
        try {
            for (FileItem fileItem : fileItems) {
                String name = fileItem.getName();
                System.out.println(name);
                if (StringUtils.isNoneBlank(fileItem.getName())) {
                    if (!fileItem.isFormField()) {
                        //保留扩展名，使用uuid重命名文件
                        String s = UUID.randomUUID().toString();
                        fineName = s + '.' + (fileItem.getName().split("\\.")[fileItem.getName().split("\\.").length - 1]);
                        File file = new File(path, uploadDir);
                        if (!file.isDirectory()) {
                            file.mkdirs();
                        }
                        fileItem.write(new File(file, fineName));
                        flag = true;
                    }
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            sqlSession = MapperFactory.getSqlSession();
            question = BeanUtil.fillBean(fileItems, Question.class);
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            String s = UUID.randomUUID().toString();
            question.setId(s);
            question.setCreateTime(new Date());
            questionDao.save(question);
            if (flag) {
                question.setPicture(uploadDir + "/" + fineName);
                questionDao.updatePicture(question);
            }
            //提交事务
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            //如果提交事务失败则回滚事务
            TransactionUtil.rollback(sqlSession);
            //并抛出运行时异常
            throw new RuntimeException(e);
            // TODO 后期添加实现记录日志功能
        } finally {
            TransactionUtil.close(sqlSession);
        }

    }

    @Override
    public void delete(Question question, String path) {
        SqlSession sqlSession = null;
        try {
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);

            String picture = questionDao.findById(question.getId()).getPicture();
            File file = new File(path, picture);
            file.delete();

            questionDao.delete(question);
            //提交事务
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            //如果提交事务失败则回滚事务
            TransactionUtil.rollback(sqlSession);
            //并抛出运行时异常
            throw new RuntimeException(e);
            // TODO 后期添加实现记录日志功能
        } finally {
            TransactionUtil.close(sqlSession);
        }
    }

    @Override
    public void update(List<FileItem> fileItems, String path) {
        SqlSession sqlSession = null;
        Question question = null;
        String fineName = "";
        boolean flag = false;
        try {
            for (FileItem fileItem : fileItems) {
                String name = fileItem.getName();
                System.out.println(name);
                if (StringUtils.isNoneBlank(fileItem.getName())) {
                    if (!fileItem.isFormField()) {
                        String s = UUID.randomUUID().toString();
                        fineName = s + '.' + (fileItem.getName().split("\\.")[fileItem.getName().split("\\.").length - 1]);
                        File file = new File(path, uploadDir);
                        if (!file.isDirectory()) {
                            file.mkdirs();
                        }
                        fileItem.write(new File(file, fineName));
                        flag = true;
                    }
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            question = BeanUtil.fillBean(fileItems, Question.class);
            question.setUpdateTime(new Date());
            if (flag) {
                String picture = questionDao.findById(question.getId()).getPicture();
                if (picture != null) {
                    File file = new File(path, picture);
                    file.delete();
                }
                question.setPicture(uploadDir + "/" + fineName);
                questionDao.updatePicture(question);
            }
            questionDao.update(question);
            //提交事务
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            //如果提交事务失败则回滚事务
            TransactionUtil.rollback(sqlSession);
            //并抛出运行时异常
            throw new RuntimeException(e);
            // TODO 后期添加实现记录日志功能
        } finally {
            TransactionUtil.close(sqlSession);
        }
    }

    @Override
    public Question findById(String id) {
        SqlSession sqlSession = null;
        try {
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            return questionDao.findById(id);
        } catch (Exception e) {
            //并抛出运行时异常
            throw new RuntimeException(e);
            // TODO 后期添加实现记录日志功能
        } finally {
            TransactionUtil.close(sqlSession);
        }
    }

    @Override
    public List<Question> findAll() {
        SqlSession sqlSession = null;
        try {
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            return questionDao.findAll();
        } catch (Exception e) {
            //并抛出运行时异常
            throw new RuntimeException(e);
            // TODO 后期添加实现记录日志功能
        } finally {
            TransactionUtil.close(sqlSession);
        }
    }

    @Override
    public PageInfo findPage(int page, int size) {
        SqlSession sqlSession = null;
        try {
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            PageHelper.startPage(page, size);
            List<Question> all = questionDao.findAll();
            return new PageInfo(all);
        } catch (Exception e) {
            //并抛出运行时异常
            throw new RuntimeException(e);
            // TODO 后期添加实现记录日志功能
        } finally {
            TransactionUtil.close(sqlSession);
        }
    }


    @Override
    public void getReport(String path) throws IOException {

        //获取对应要展示的数据
        SqlSession sqlSession = null;
        List<Question> questionList = null;
        try {
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            //3.调用Dao层操作
            questionList = questionDao.findAll();
        } catch (Exception e) {
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        InputStream inputStream = new FileInputStream(path+"template/question_template.xlsx");

        //获取到对应的Excel文件，工作簿文件
        Workbook wb = new XSSFWorkbook(inputStream);
        //2.获得工作表
        Sheet s = wb.getSheet("questionList");
        //设置表格边框
        CellStyle cs_field = wb.createCellStyle();
        cs_field.setAlignment(HorizontalAlignment.CENTER);
        cs_field.setBorderTop(BorderStyle.THIN);
        cs_field.setBorderBottom(BorderStyle.THIN);
        cs_field.setBorderLeft(BorderStyle.THIN);
        cs_field.setBorderRight(BorderStyle.THIN);
        //制作数据区
        int row_index = 0;
        for (Question q : questionList) {
            int cell_index = 0;
            Row row_temp = s.createRow(3 + row_index++);

            Cell cell_data_1 = row_temp.createCell(1 + cell_index++);
            cell_data_1.setCellValue(q.getId());    //++
            cell_data_1.setCellStyle(cs_field);

            Cell cell_data_2 = row_temp.createCell(1 + cell_index++);
            cell_data_2.setCellValue(q.getCompanyId());    //++
            cell_data_2.setCellStyle(cs_field);

            Cell cell_data_3 = row_temp.createCell(1 + cell_index++);
            cell_data_3.setCellValue(q.getCatalogId());    //++
            cell_data_3.setCellStyle(cs_field);

            Cell cell_data_4 = row_temp.createCell(1 + cell_index++);
            cell_data_4.setCellValue(q.getRemark());    //++
            cell_data_4.setCellStyle(cs_field);

            Cell cell_data_5 = row_temp.createCell(1 + cell_index++);
            cell_data_5.setCellValue(q.getSubject());    //++
            cell_data_5.setCellStyle(cs_field);

            Cell cell_data_6 = row_temp.createCell(1 + cell_index++);
            cell_data_6.setCellValue(q.getPicture());    //++
            cell_data_6.setCellStyle(cs_field);

            Cell cell_data_7 = row_temp.createCell(1 + cell_index++);
            cell_data_7.setCellValue(q.getAnalysis());    //++
            cell_data_7.setCellStyle(cs_field);

            Cell cell_data_8 = row_temp.createCell(1 + cell_index++);
            cell_data_8.setCellValue(q.getType());    //++
            cell_data_8.setCellStyle(cs_field);

            Cell cell_data_9 = row_temp.createCell(1 + cell_index++);
            cell_data_9.setCellValue(q.getDifficulty());    //++
            cell_data_9.setCellStyle(cs_field);

            Cell cell_data_10 = row_temp.createCell(1 + cell_index++);
            cell_data_10.setCellValue(q.getIsClassic());    //++
            cell_data_10.setCellStyle(cs_field);

            Cell cell_data_11 = row_temp.createCell(1 + cell_index++);
            cell_data_11.setCellValue(q.getState());    //++
            cell_data_11.setCellStyle(cs_field);

            Cell cell_data_12 = row_temp.createCell(1 + cell_index++);
            cell_data_12.setCellValue(q.getReviewStatus());    //++
            cell_data_12.setCellStyle(cs_field);
        }
        //创建一个文件对象，作为excel文件内容的输出文件
        File f = new File(path+"template/question.xlsx");
        //输出时通过流的形式对外输出，包装对应的目标文件
        OutputStream os = new FileOutputStream(f);
        //将内存中的workbook数据写入到流中
        wb.write(os);
        wb.close();
        os.close();
    }

}

